<?php

/**
 * Name: OSS上传服务
 * User: Silent
 * Date: 2025-11-17
 * Time: 17:35:00
 */

namespace App\Services\Upload;

use Illuminate\Support\Facades\Storage;
use Exception;

class OssUploadService
{
    protected $disk;

    public function __construct()
    {
        $this->disk = Storage::disk('oss');
    }

    /**
     * 上传头像文件到OSS
     *
     * @param string $filePath 本地文件路径
     * @param string $filename 上传后的文件名（不包含路径）
     * @param string $directory 上传目录，默认为avatars
     * @return array ['success' => bool, 'url' => string, 'message' => string]
     */
    public function uploadAvatar($filePath, $filename, $directory = 'avatars')
    {
        try {
            // 检查文件是否存在
            if (!file_exists($filePath)) {
                return [
                    'success' => false,
                    'url' => '',
                    'message' => '文件不存在'
                ];
            }

            // 构建OSS路径
            $ossPath = $directory . '/' . $filename;

            // 读取文件内容
            $fileContent = file_get_contents($filePath);
            if ($fileContent === false) {
                return [
                    'success' => false,
                    'url' => '',
                    'message' => '无法读取文件内容'
                ];
            }

            // 上传到OSS
            $result = $this->disk->put($ossPath, $fileContent);

            if (!$result) {
                return [
                    'success' => false,
                    'url' => '',
                    'message' => 'OSS上传失败'
                ];
            }

            // 获取文件URL
            $url = $this->disk->url($ossPath);

            \Log::info('头像上传OSS成功', [
                'local_path' => $filePath,
                'oss_path' => $ossPath,
                'url' => $url
            ]);

            return [
                'success' => true,
                'url' => $url,
                'message' => '上传成功',
                'oss_path' => $ossPath
            ];

        } catch (Exception $e) {
            \Log::error('OSS上传失败', [
                'file_path' => $filePath,
                'filename' => $filename,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'url' => '',
                'message' => 'OSS上传异常：' . $e->getMessage()
            ];
        }
    }

    /**
     * 直接上传文件内容到OSS
     *
     * @param string $content 文件内容
     * @param string $filename 文件名
     * @param string $directory 目录
     * @return array
     */
    public function uploadContent($content, $filename, $directory = 'avatars')
    {
        try {
            $ossPath = $directory . '/' . $filename;

            $result = $this->disk->put($ossPath, $content);

            if (!$result) {
                return [
                    'success' => false,
                    'url' => '',
                    'message' => 'OSS上传失败'
                ];
            }

            $url = $this->disk->url($ossPath);

            \Log::info('内容直接上传OSS成功', [
                'oss_path' => $ossPath,
                'url' => $url,
                'size' => strlen($content)
            ]);

            return [
                'success' => true,
                'url' => $url,
                'message' => '上传成功',
                'oss_path' => $ossPath
            ];

        } catch (Exception $e) {
            \Log::error('OSS内容上传失败', [
                'filename' => $filename,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'url' => '',
                'message' => 'OSS上传异常：' . $e->getMessage()
            ];
        }
    }

    /**
     * 删除OSS上的文件
     *
     * @param string $ossPath OSS路径
     * @return bool
     */
    public function deleteFile($ossPath)
    {
        try {
            return $this->disk->delete($ossPath);
        } catch (Exception $e) {
            \Log::error('OSS删除文件失败', [
                'oss_path' => $ossPath,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }

    /**
     * 生成唯一的头像文件名
     *
     * @param string $nickname 昵称
     * @param string $userId 用户ID
     * @return string
     */
    public function generateAvatarFilename($nickname, $userId = null)
    {
        $timestamp = time();
        $randomStr = substr(md5(uniqid()), 0, 8);

        if ($userId) {
            return "avatar_{$userId}_{$timestamp}_{$randomStr}.png";
        }

        // 使用昵称生成文件名
        $nicknameHash = substr(md5($nickname), 0, 8);
        return "avatar_{$nicknameHash}_{$timestamp}_{$randomStr}.png";
    }

    /**
     * 检查OSS配置是否有效
     *
     * @return bool
     */
    public function isConfigured()
    {
        try {
            $config = config('filesystems.disks.oss');
            return !empty($config['access_id']) &&
                   !empty($config['access_key']) &&
                   !empty($config['bucket']) &&
                   !empty($config['endpoint']);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 获取OSS配置信息（隐藏敏感信息）
     *
     * @return array
     */
    public function getConfigInfo()
    {
        $config = config('filesystems.disks.oss');

        return [
            'configured' => $this->isConfigured(),
            'bucket' => $config['bucket'] ?? '',
            'endpoint' => $config['endpoint'] ?? '',
            'cdn_domain' => $config['cdnDomain'] ?? '',
            'ssl' => $config['ssl'] ?? false,
            'is_cname' => $config['isCName'] ?? false
        ];
    }
}
